<?php

namespace app\stores\controller\miniapp;

use app\BaseController;
use app\beautiful\logic\printer\PrinterLogic;
use app\beautiful\model\goods\GoodsOtherSkuDetailModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\order\BuyOrderModel;
use app\beautiful\model\order\GoodsOrderModel;
use app\common\logic\DataLogic;
use app\common\model\BannerModel;
use app\common\model\MemberMoneyDetailModel;
use app\common\model\ShopBrandModel;
use app\common\model\ShopDetailModel;
use app\common\model\ShopModel;
use app\stores\logic\ConDataLogic;
use app\stores\model\CityModel;
use app\stores\model\member\MemberSearchModel;


class Index extends BaseController{
    /*banner*/
    public function bannerIndex(){
        $banner = BannerModel::with(['link'])->where(['is_effect'=>1,'is_delete'=>0])->select()->toArray();
        return $this->success($banner);
    }

    /*拼团、秒杀*/
    public function activities(){
        $city =  $this->request->param('city','成都市');

        $ConDataLogic = new ConDataLogic();

        //拼团
        $pinTuan = $ConDataLogic->getData(['key'=>'pintuan','num'=>3,'city'=>$city]);

        if($pinTuan['pintuan']){
            $pinTuan['pintuan'] = addTwoData($pinTuan['pintuan'],['type'=>1]);
        }

        //秒杀
        $flashSale=$ConDataLogic->getData(['key'=>'miaosha','num'=>3,'city'=>$city]);

        if($flashSale['miaosha']){
            $flashSale['miaosha'] = addTwoData($flashSale['miaosha'],['type'=>2]);
        }

        $data = array_merge($pinTuan['pintuan'],$flashSale['miaosha']);

        return $this->success($data);

    }
    /*附近好店*/
    public function shopIndex(){
        $search =  $this->request->param('search');
        $lng =  $this->request->param('lng/f',0);
        $lat =  $this->request->param('lat/f',0);
        $city =  $this->request->param('city','成都市');
        $where = [
            ['s.status','in',[0,1,8]],
            ['s.shop_id','<>',35],
            ['s.open_status','=',1],
//            ['sd.city','=',$city]
        ];

        if(!empty($search)) $where[]=['s.name','like','%'.$search.'%'];
        $data = $this->shopList($where,$lat,$lng,$this->request->limit,$this->request->page);

        //添加记录
        if($search) addSearch($this->request->memberId,$search);


        return $this->success($data);
    }
    /*门店列表*/
    protected function shopList($where,$lat,$lng,$limit=0,$page=0){
        $filed = "s.shop_id,s.name,s.brand_id,sd.logo,sd.door_license_plate,sd.address,sd.per_money,(6378.138 * 2 * asin(sqrt(pow(sin((sd.t_lat * pi() / 180 - {$lat} * pi() / 180) / 2),2)
             + cos(sd.t_lat * pi() / 180) * cos({$lat} * pi() / 180) * pow(sin((sd.t_lng * pi() / 180 - {$lng} * pi() / 180) / 2),2))) * 1000) as distance";
        $order = ['distance'=>'asc'];
        $shop_model = new ShopModel();
        $data = $shop_model->getList($where,$filed,$page,$limit,$order);
        $list = $data['list'];
        foreach ($list as $k=>$v){
            $list[$k]['brand'] = '';
            $brand = ShopBrandModel::with(['pbrand'=>function($query){
                $query->where(['is_effect'=>1,'is_delete'=>0]);
            }])->where(['is_effect'=>1,'is_delete'=>0,'id'=>$v['brand_id']])->find();

            if($brand) $list[$k]['brand'] = $brand->pbrand?$brand->pbrand->name.'/'.$brand->name:$brand->name;
            $list[$k]['order_count'] = $this->getOrderCount(['shop_id'=>$v['shop_id'],'is_paid'=>1]);
            //套餐
            $goods = $this->goodsList(['shop_id'=>$v['shop_id'],'status'=>1,'is_delete'=>0,'type'=>3,'online_sales'=>1],3);
            //产品
            if(empty($goods)){
                $goods = $this->goodsList(['shop_id'=>$v['shop_id'],'status'=>1,'is_delete'=>0,'type'=>2,'online_sales'=>1],3);
            }

            $list[$k]['goods'] = $goods;
        }
        $data['list'] = $list;
        return $data;
    }
    //获取门店订单数
    protected function getOrderCount($where){
        $goods_order_count = GoodsOrderModel::where($where)->count();
        $buy_order_count = BuyOrderModel::where($where)->count();
        return $goods_order_count+$buy_order_count;
    }
    /*获取分类产品(无门店id)*/
    protected function getGoodsList($where,$order=[],$limit=0,$page=0)

    {
        $field = "goods_id,shop_id,cover_img,name,original_price,vip_price,crossed_price,quota,take_count,fictitious_take_count,category_id,discount_detail,vip_discount_type,type,unit_id";
        $goodsModel = GoodsModel::with(['unit','sku'=>function($query){
            $query->with(['unit'=>function($query1){
                $query1->where(['is_delete'=>0])->field('other_sku_detail_id,group_detail_name');
            }])->where([
                ['is_delete','=',0],
                ['quota','>',0],
            ])->json(['discount_detail'],true);
        }])->field($field)->json(['discount_detail'],true);
        $append = [];

        $data = DataLogic::getDataList($goodsModel,$where,$order,'',$limit,$page,$append);

        $list = $data['list'];

        $member = $this->request->member;
        if(!$member && $this->request->memberId){
            $member = MemberModel::find($this->request->memberId);
        }
        foreach ($list as $k=>$v){
            $shop_id = $v['shop_id'];
            $hx_price = $v['type']==3?$v['original_price']:$v['crossed_price'];
            $return = getMemberPrice($member,$shop_id,$v,$hx_price,$v['type']);
            if($return){
                $list[$k]['price'] = sprintf("%.2f", $return['price']);;
                $list[$k]['discount'] = $return['discount'];
            }
            if($v['sku']){

                $sku = skuMemberPrice($v['vip_discount_type'],$v['sku'],$member,$shop_id,$v['type']);

                $list[$k]['sku'] = $sku;
            }
            //单位
            $unit = GoodsOtherSkuDetailModel::where(['is_delete'=>0,'other_sku_detail_id'=>$v['unit_id']])->find();
            $list[$k]['unit'] = $unit?$unit['group_detail_name']:null;
        }

        $data['list'] = $list;
        return $data;

    }

    protected function goodsList($where,$limit){
        $member = new MemberModel();
        $member->member_id = $this->request->memberId;
        $goods = GoodsModel::where($where)
            ->field('origin_type,shop_id,goods_id,name,original_price,crossed_price,total_value,cover_img,vip_discount_type,discount_detail,type')
            ->json(['discount_detail'],true)
            ->limit($limit)
            ->order(['sort'=>'desc','add_time'=>'desc'])
            ->select()->toArray();
        foreach ($goods as $k=>$v){
            $hx_price = $v['type']==3?$v['total_value']:$v['original_price'];
            $return = getMemberPrice($member,$v['shop_id'],$v,$hx_price,$v['type']);
            $goods[$k]['price'] = $return['price'];
            $goods[$k]['discount'] = $return['discount'];

        }
        //$goods = getPrice($goods,$member,1);

        return $goods;
    }
    /*获取搜索记录*/
    public function searchIndex(){
        $search_model = new MemberSearchModel();
        $return = $search_model->getList(['member_id'=>$this->request->memberId],['search_id'=>'desc'],1,10,'content');
        return $this->success($return);
    }
    /*删除搜索*/
    public function delSearch(){
        $search_model = new MemberSearchModel();
        $search_model->del(['member_id'=>$this->request->memberId]);
        return $this->success('删除成功');
    }
    /*搜索*/
    public function search(){
        $type = $this->request->param('type/d',1);//1门店2产品
        $search =  $this->request->param('search');
        $lng =  $this->request->param('lng/f',0);
        $lat =  $this->request->param('lat/f',0);
        $city =  $this->request->param('city','成都市');

        //门店
        $s_where = [
            ['s.status','=',8],
//            ['sd.city','=',$city]
        ];
        if(!empty($search)) $s_where[]=['s.name','like','%'.$search.'%'];

        //产品
        $shop_model = new ShopModel();
        $return = $shop_model->getList(['s.status'=>8,'sd.city'=>$city],$filed='s.shop_id',0,0);
        $shop_list = $return['list'];
        if($shop_list){
            $shop_ids = array_column($shop_list,'shop_id');
        }else{
            $shop_ids = [];
        }

        $g_where=[
            ['shop_id','In',$shop_ids],

            ['status','=',1],

            ['is_delete','=',0],

            ['is_open_yu','=',0],

            ['quota','>',0],

            ['type','=',2]

        ];
        if(!empty($search)) $g_where[]=['name','like','%'.$search.'%'];

        if($type==1){
            $list = $this->shopList($s_where,$lat,$lng,$this->request->limit,$this->request->page);
            $other_list = $this->getGoodsList($g_where);
            $other_list['count'] = $other_list['total'];
        }else{
            $order=['sort'=>'desc','fictitious_take_count'=>'desc','vip_price'=>'desc'];
            $list = $this->getGoodsList($g_where,$order,$this->request->limit,$this->request->page);
            $list['count'] = $list['total'];
            $other_list = $this->shopList($s_where,$lat,$lng);
        }
        //添加记录
        if($this->request->memberId){
            if($search) addSearch($this->request->memberId,$search);
        }

        $list['other_count'] = $other_list['count'];
        return $this->success($list);
    }
    /*定位城市*/
    public function getCity(){
        $search =  $this->request->param('search');
        $city_model = new CityModel();
        
        //热门
        $hot_city_name = ['成都市', '北京市', '上海市', '重庆市', '广州市', '深圳市', '南京市', '天津市', '杭州市'];
        $h_where[] = ['name','In',$hot_city_name];
        $h_where[] = ['is_show','=',1];
        $h_where[] = ['id','<>',35];
        $hot_list = $city_model->getList($h_where,['city_id'=>'asc']);
        $list['hot'] = $hot_list['list'];
        
        //城市
        $where[] = ['is_show','=',1];
        $where[] = ['level','=',1];
        $where[] = ['id','<>',35];
        if(!empty($search)) $where[]=['name','like','%'.$search.'%'];
       
        $city_list = $city_model->getList($where,['city_id'=>'asc']);
        
        //直辖市、自治区
        $city_name = ['北京市', '天津市', '上海市', '重庆市', '香港特别行政区', '澳门特别行政区', '内蒙古自治区', '西藏自治区', '广西壮族自治区', '宁夏回族自治区', '新疆维吾尔自治区'];
        $c_where[]=['name','In',$city_name];
        $c_where[]=['is_show','=',1];
        $c_where[] = ['id','<>',35];
        if(!empty($search)) $c_where[]=['name','like','%'.$search.'%'];
        $c_list = $city_model->getList($c_where,['city_id'=>'asc']);
        
        $list['list'] = array_merge($city_list['list'],$c_list['list']);
        $list['count'] = count($list['list']);

        return $this->success($list);
    }

    public function notice_list(){
        $limit=$this->request->limit;
        $page=$this->request->page;
        $where=[];
        $order['a.id']='desc';
        $where['status']=0;
        $res_data=MemberMoneyDetailModel::list($where,$order,$page,$limit);

        return $this->success($res_data);
    }
    public function cs(){
        $time_type =  $this->request->param('time_type');
        $d = date('d');
        $t = date('t');
        $str = '';
        if($d==$t && in_array($d,[28,31])){
            $str = "last day of";
        }
        if($time_type == 1){
            $vip_start_time = date("Y-m-d")." 00:00:00";
            $vip_end_time = date("Y-m-d",strtotime($str."+1 year"))." 23:59:59";
        }
        if($time_type == 3){
            $vip_start_time = date("Y-m-d")." 00:00:00";
            $vip_end_time = date("Y-m-d",strtotime($str."+1 month"))." 23:59:59";

        }
        if($time_type == 4){
            $vip_start_time = date("Y-m-d")." 00:00:00";
            $vip_end_time = date("Y-m-d",strtotime($str."+3 month"))." 23:59:59";
        }
        var_dump($vip_start_time);
        var_dump($vip_end_time);
        exit;

        $order_id = $this->request->param('order_id/d');
        if( null === $order = \app\beautiful\model\order\GoodsOrderModel::find($order_id)){
            return $this->error('订单不存在');
        }
        //打印机
        if($order->logistics_type == 1){
            $type = 'kuaidi';
        }

        if($order->logistics_type == 2){
            $type = 'self';
        }
        if($order->logistics_type == 3){
            $type = 'city';
        }
        if(in_array($order->logistics_type,[1,2,3])){
            //判断是否有分区打印的产品
            $return_goods_produce = goodsProduce($order_id);
            $prints = $return_goods_produce['prints'];
            $produce_printer_ids = [];
            if($prints){
                $printer_logic = new \app\stores\logic\printer\PrinterLogic($order->shop_id);
                $produce_printer_ids = $printer_logic->producePrint($type,$order_id,$prints);
            }
            //原来的打印排除已分区打印的打印机
            $printer_logic = new PrinterLogic($order->shop_id);
            $printer_logic->print($type,$order_id,$produce_printer_ids);

        }
        exit;
        $orderId = 0;
        $order = \app\stores\model\order\BuyOrderModel::where(['buy_order_id'=>$orderId,'member_id'=>1])->find();
        mix_pay_money($order,$order->pay_info,1);
        exit;
        $lat1 = $this->request->param('lat1');
        $lng1 = $this->request->param('lng1');
        $lat2 = $this->request->param('lat2');
        $lng2 = $this->request->param('lng2');
        $re=get_distance($lat1, $lng1, $lat2, $lng2);
        var_dump($re);
    }

}

